package io.renren.common.utils;

import io.renren.common.exception.RRException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * User: 齐丹枫
 * Date: 2018/12/24
 * Time: 16:52
 * To change this template use File | Settings | File Templates.
 * Description:
 */
public class ValidateFileTypeUtil {

    public static Workbook  validate(MultipartFile file){
        Workbook workbook = null;

        if (file.isEmpty()){
            throw new RRException("上传文件不能为空");
        }
        String filename = file.getOriginalFilename();
        String substring = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
        try {
            if (substring.equals("xls")){
                workbook =new HSSFWorkbook(file.getInputStream());
            }else if(substring.equals("xlsx")){
                workbook = new XSSFWorkbook(file.getInputStream());
            }else{
                throw new RRException("文件格式错误(xlsx,xls)");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return workbook;
    }

}
